//创建用户相关的小仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo } from '@/api/user'
import type { loginFormData } from '@/api/user/type'
import { constantRoute } from '@/router/routes'

let useUserStore = defineStore('User', {
    state: () => {
        return {
            token: '', //从本地获取token
            mennuRoutes: constantRoute, //仓库存储生成菜单需要的路由
            username: '',
            avatar: '',
        }
    },
    persist: true, //持久化(localStorage)
    actions: {
        //登入
        async userLogin(data: loginFormData) {
            let result = await reqLogin(data)
            //登入成功后，将token存储到仓库中
            if (result.code === 200) {
                this.token = result.data.token as string
                return 'ok' //保证当前函数返回值是一个promise对象，返回promise后，就可以在组件中使用.then()方法了！！！
            } else {
                return Promise.reject(new Error(result.data.message))
            }
        },
        //获取用户信息
        async getUserInfo() {
            let result = await reqUserInfo()
            if (result.code === 200) {
                this.username = result.data.username
                this.avatar = result.data.avatar
                return result.data
            } else {
                return Promise.reject(new Error(result.data.message))
            }
        },
        //退出登录
        userLogout() {
            this.token = ''
            this.username = ''
            this.avatar = ''
        },
    },
    getters: {},
})

export default useUserStore
